﻿using PeiYue.Common;
using PeiYue.IRepository.Base;
using PeiYue.IServices.Store;
using PeiYue.Model.Dto.Store;
using PeiYue.Model.Models.Store;
using PeiYue.Services.BASE;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PeiYue.Services.Store
{
    public class DeliveryServices : BaseServices<DeliveryRecordDao>, IDeliveryServices
    {
        IBaseRepository<DeliveryRecordDao> _dal;
        public DeliveryServices(IBaseRepository<DeliveryRecordDao> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
        }

        /// <summary>
        /// 获取仓库拣选日志
        /// </summary>
        /// <param name="barCode"></param>
        /// <param name="deliveryDate"></param>
        /// <returns></returns>
        public async Task<SortingLogDto> GetSortingLogDto(string barCode, DateTime deliveryDate)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select j.数量 as Qty,j.单价 as Price,j.销售ID as SaleId,j.条码 as BarCode  from  供应链.dbo.v销售发货表头 h  ");
            strSql.Append("Left join  供应链.dbo.v销售发货表体 b on h.单号=b.单号 ");
            strSql.Append("Left join 供应链.dbo.v仓库拣选日志 j  on b.销售ID = j.销售ID  ");
            strSql.Append("where  j.条码=@barCode and  h.日期>=@deliveryDate ");
            List<SugarParameter> sugarParameters = new List<SugarParameter>();
            sugarParameters.Add(new SugarParameter("@barCode", barCode));
            DateTime date = (DateTime.Now.Hour >= int.Parse(Appsettings.app(new string[] { "QueryHour", "ReceiptHour" })) ? DateTime.Now.AddDays(1).Date : DateTime.Now.Date);
            sugarParameters.Add(new SugarParameter("@deliveryDate", date));
            var list = await _dal.SqlQueryList<SortingLogDto>(strSql.ToString(), sugarParameters);
            return list.FirstOrDefault();
        }

        /// <summary>
        /// 获取已投递记录
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<List<DeliveryRecordDto>> GetDeliveryRecordList(long userId)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select Id,(Priority+CustomerCode) as CustomerCode ,SkuName,SkuQty,SkuSpec,OrderDetailId,BarCode  ");
            strSql.Append(" from DeliveryRecord where UpdateUser=@UpdateUser and UpdateTime>=@UpdateTime and  Status=0  ");
            strSql.Append(" order by Id desc ");
            List<SugarParameter> sugarParameters = new List<SugarParameter>();
            sugarParameters.Add(new SugarParameter("@UpdateUser", userId));
            sugarParameters.Add(new SugarParameter("@UpdateTime", DateTime.Now.Date));
            return await _dal.SqlQueryList<DeliveryRecordDto>(strSql.ToString(), sugarParameters);
        }
    }
}
